<?php

// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

namespace Card\Controller;
use Think\Controller\RestController;
/**
 * 前台首页控制器
 * 主要获取首页聚合数据
 */
class CardController extends RestController {
    protected $needLogin = false;           //是否必须登录
    protected $_login_name = 'cardMemberId'; //登录session名称，给点是不和社区冲突
    protected $_member = NULL;              //登录信息
    protected $_session_memberId = 'memberId';  //登录session名称，和社区一样
    protected $_session_memberInfo = 'memberInfo'; //用户信息数组
    protected $_isGuestKey = 'isGuest'; //活动的，必须为false
	

    protected function status403()
    {
        @header('HTTP/1.1 403 Forbidden'); 
        @header("status: 403 Forbidden"); 
        exit('<html><head><title>403 Forbidden</title></head><body bgcolor="white">403 Forbidden</body></html>');
    }
    
    public function _empty() {
        $this->status403();
    }
	
	/**
    *登录
    *
    */
    protected function cardLogin($memberId,$memberInfo)
    {  
    	$info=array(
			'id'=>$memberInfo['memberId'],
			'username'=>$memberInfo['username'],
			'nickname'=>$memberInfo['nickName'],
			'headimg'=>$memberInfo['headImgUrl'],
			'qrcode'=>$memberInfo['memberQrCode'],
			'memberId'=>$memberInfo['memberId'],

		);
    	if(intval($memberId) > 0 && $info){
        session($this->_session_memberId, $memberId);
        session($this->_session_memberInfo, $info);
        session($this->_isGuestKey, false);
        setcookie ("loginCookie", 'ok', 0, '/' , 'wttai.com');
        $_COOKIE["loginCookie"] == 'ok';
    	}

    }
	
	
    /**
    *初始化方法
    *
    */
	protected function _initialize()
	{
        //var_dump(get_included_files()); exit;
        //var_dump($_COOKIE,$_SESSION);exit;
       
         $this->header();   
        /*读取站点配置*/
        $config = api('Config/lists');
        C($config); //添加配置
        if (!C('WEB_SITE_CLOSE')) {
            $this->error(L('_ERROR_WEBSITE_CLOSED_'));
        }
        //session必须为空，是为了和社区同步登陆
        C('SESSION_PREFIX', '');
        //过滤 card.wttai.com/card
        $url =  $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
        if (strpos($url,'card.wttai.com/card') === false){
            $this->checkMobile();
        }

        /*配置文件结束*/

        /*检查登录*/
        $this->checkLogin();
        /*检查登录结束*/



        /*必须登录*/
         if ($this->needLogin) {
            $this->mustLogin();//必须登录
        }


	}
	


    /**
    *必须登录
    *
    */
    protected function mustLogin()
    {
        if (!$this->checkLogin()) {
            $return_url = "http://".$_SERVER['HTTP_HOST'].__SELF__;
            $jump_url = C('SHEQU_DOMAIN').'/member/login.html?return_url='.$return_url;
            if (IS_AJAX) {
                return $this->tips(403, '必须登录', array('jump_url' => $jump_url));
            }
            return redirect($jump_url);
        }
    }

    /**
    *登录
    */
    protected function checkLogin()
    {       
        $memberId = intval(session($this->_session_memberId));
        //var_dump($memberId,$_COOKIE,$_SESSION);exit;
        if ($memberId > 0) {
            if (isset($_COOKIE["loginCookie"])) {
                //判断是否是退出状态 
                if ($_COOKIE["loginCookie"] == 'logout') {
                    session(null);
                    return false;
                }
            }

            //判断是否绑定手机，决定跳转至绑定页
            if(!@$_COOKIE["phone_bind"]){
                header("location:".C('SHEQU_DOMAIN')."/member/bind-phone.html?email=1");
            }

        
            $this->_member = session($this->_session_memberInfo);
            return true;
        }
        return false;
    }
	
	
  /**
  *是否是手机
  */
  protected function isMobile()
  {

	// session($this->_session_memberId, 1173);
	//session($this->_session_memberInfo, $a);
    //判断手机发送的客户端标志,兼容性有待提高
    if (isset ($_SERVER['HTTP_USER_AGENT'])) {
        $clientkeywords = array (
            'nokia','sony','ericsson','mot','samsung','htc','sgh','lg','sharp','sie-','philips',
            'panasonic','alcatel','lenovo','iphone','ipod','blackberry','meizu','android','netfront',
            'symbian','ucweb','windowsce','palm','operamini','operamobi','openwave','nexusone','cldc',
            'midp','wap','mobile','SymbianOS','NEC','TCL','BIRD','DBTEL','Dopod','HAIER','MOT-',
            'SonyEricsson','Amoi','ZTE'
        );
        // 从HTTP_USER_AGENT中查找手机浏览器的关键字
        if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))) {
            return true;
            //return false;
        }
    }
    return false;
  }
  
  /**
  *检查是否是手机，是跳转
  *
  *
  ***/
  protected function checkMobile()
  {
    if ($this->isMobile()) {
      $action = ACTION_NAME;

      $id = I('get.id',0,'int');
        if ($action == 'index'){
            $id = I('get.category',0);
            $url = sprintf(C(MSHEQU_DOMAIN_M),"?categoryId=".$id);
        }elseif ($action == 'gallery') {
             $url = sprintf(C(MSHEQU_DOMAINPIC),"?atlaId=".$id);     
        } elseif ($action == 'gallery_detail') {
            $url = sprintf(C(MSHEQU_DOMAINPIC_DETAIL),"?id=".$id);
        } else {
            $url = C(MSHEQU_DOMAIN);
        }
        
        if($action != 'qrvcf'){
            redirect($url);  
        }

      
    }
  }

   /*
   * 退出
   *
   */
    public function  loginout(){
    
        session($this->_session_memberId,null);
        session($this->_session_memberInfo,null);
        setcookie ("loginCookie", 'logout', 0, '/' , 'wttai.com');
        @setcookie ('phone_bind', '', time() - 3600, '/' , 'wttai.com');
        $this->redirect("/");
  }  
  
  
         /*
         * 首页导航控制器
         */
        public function header(){

            $channel = M('channel');
            $header_info = $channel->order('sort desc,id')->where(['status'=>1])->select();
            $tree = $this->arrToTree($header_info,$pid=0);
            $this->assign('header', $tree);
        }

        //导航递归函数
        private function arrToTree($data,$pid=0){  
            $tree = array();  
            foreach($data as $k => $v){  
                if($v['pid'] == $pid){
                    $son = $this->arrToTree($data,$v['id']);
                        $v['class'] = $son; 
                        if (empty($v['class'])){
                            unset($v['class']);
                        }
                        $tree[] = $v;
                }  
            }          
            return $tree;  
        }
}
